﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Workflow.ComponentModel;
using System.Workflow.ComponentModel.Design;
using System.Workflow.ComponentModel.Compiler;
using System.Workflow.ComponentModel.Serialization;
using System.Workflow.Runtime;
using System.Workflow.Activities;
using System.Workflow.Activities.Rules;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Diagnostics;
using Microsoft.ResourceManagement.Utilities;
using Microsoft.IdentityManagement.WebUI;
using Microsoft.ResourceManagement.Workflow.Activities;
using Microsoft.IdentityManagement.WebUI.Controls;
using Microsoft.IdentityManagement.WebUI.Controls.Resources;

namespace Ensynch.ILM2.WebUI.Controls
{
	class DiagnosticActivitySettingsPart : ActivitySettingsPart
	{
        protected override void CreateChildControls()
        {
            try
            {
                this.InitializeControls();
                base.CreateChildControls();
            }
            catch (Exception ex)
            {
                SimpleLogFunction("Activitites.CreateChildControls", ex.Message, EventLogEntryType.Error, 1000, 100);
            }
        }

        public override Activity GenerateActivityOnWorkflow(SequentialWorkflow workflow)
        {
            try
            {
                this.SimpleLogFunction("GenerateActivityOnWorkflow", "Starting Activity Generation", EventLogEntryType.Information, 10000, 100);
                if (!this.ValidateInputs())
                {
                    return null;
                }
                Ensynch.ILM2.Workflow.Activities.DiagnosticActivity activity =
                                                    new Ensynch.ILM2.Workflow.Activities.DiagnosticActivity();
                this.SimpleLogFunction("GenerateActivityOnWorkflow", "Activity Created", EventLogEntryType.Information, 10000, 100);
                activity.TheActivityName = GetControlString("txtTheActivityName");
                activity.LogFolder = GetControlString("txtFilePath");
                activity.LogFile = GetControlString("txtFileName");
 
                this.SimpleLogFunction("GenerateActivityOnWorkflow", "Activity Properties Set", EventLogEntryType.Information, 10000, 100);
                
                return activity;
            }
            catch (Exception ex)
            {
                SimpleLogFunction("GenerateActivityOnWorkflow Error", ex.Message, EventLogEntryType.Error, 1000, 100);
                return null;
            }
        }

        public override void LoadActivitySettings(Activity activity)
        {
            Ensynch.ILM2.Workflow.Activities.DiagnosticActivity activity2 =
                        activity as Ensynch.ILM2.Workflow.Activities.DiagnosticActivity;
            if (activity2 != null)
            {
                SetTextBoxValue("txtTheActivityName", activity2.TheActivityName);
                SetTextBoxValue("txtFilePath", activity2.LogFolder);
                SetTextBoxValue("txtFileName", activity2.LogFile);
            }
        }

        public override ActivitySettingsPartData PersistSettings()
        {
            ActivitySettingsPartData data = new ActivitySettingsPartData();
            data["TheActivityName"] = GetControlString("txtTheActivityName");
            data["LogFolder"] = GetControlString("txtFilePath");
            data["LogFile"] = GetControlString("txtFileName");
            return data;
        }

        public override void RestoreSettings(ActivitySettingsPartData data)
        {
            if (data != null)
            {
                SetTextBoxValue("txtTheActivityName", data["TheActivityName"] as string);
                SetTextBoxValue("txtFilePath", data["LogFolder"] as string);
                SetTextBoxValue("txtFileName", data["LogFile"] as string);
            }
        }

        public override void SwitchMode(ActivitySettingsPartMode mode)
        {
            bool flag = mode != ActivitySettingsPartMode.Edit;
            SetControlAccess("txtTheActivityName", flag);
            SetControlAccess("txtFilePath", flag);
            SetControlAccess("txtFileName", flag);
        }

        public override string Title
        {
            get
            {
                return "Ensynch Diagnostic Activity: " + GetControlString("txtTheActivityName");
            }
        }


        public override bool ValidateInputs()
        {
            return true;
        }

        #region Utility Functions

        private void InitializeControls()
        {
            Table child = new Table();
            //child.Style.Add("background-image", "/Images/EnsynchSwish.jpg");
            child.Width = Unit.Percentage(100.0);
            child.BorderWidth = 0;
            child.CellPadding = 2;
            //
            // We need an activity name for our instance, a folder path to where to write the file and a text box to hold our filename
            // which we will default to myLog.txt
            //
            child.Rows.Add(AddTableRow("Activity Name:", "txtTheActivityName", 64, false, "Diagnostics"));
            child.Rows.Add(AddTableRow("File Folder Path:", "txtFilePath", 256, false, "C:\\"));
            child.Rows.Add(AddTableRow("Diagnostic File Name:", "txtFileName", 64, false, "LogFile.txt"));

            this.Controls.Add(child);
        }

        private TableRow AddTableRow(String labelText, String controlID, int maxLength, Boolean multiLine, string DefaultValue)
        {
            TableRow row = new TableRow();
            TableCell labelCell = new TableCell();
            TableCell controlCell = new TableCell();
            Label olabel = new Label();
            TextBox oText = new TextBox();
            // Add the To:
            olabel.Text = labelText;
            olabel.CssClass = base.LabelCssClass;
            labelCell.Controls.Add(olabel);
            oText.ID = controlID;
            oText.CssClass = base.TextBoxCssClass;
            oText.Text = DefaultValue;
            oText.MaxLength = maxLength;
            if (multiLine)
            {
                oText.TextMode = TextBoxMode.MultiLine;
                oText.Rows = System.Math.Min(6, (maxLength + 60) / 60);
            }
            controlCell.Controls.Add(oText);
            row.Cells.Add(labelCell);
            row.Cells.Add(controlCell);
            return row;
        }

        private void SetControlAccess(string controlID, Boolean readOnly)
        {
            TextBox oText = (TextBox)this.FindControl(controlID);
            if (oText != null)
                oText.ReadOnly = readOnly;
        }

        private string GetControlString(string controlID)
        {
            TextBox oText = (TextBox)this.FindControl(controlID);
            if (oText != null)
                return oText.Text;
            else
                return "[TextBox '" + controlID + "' Not Found";
        }

        private void SetTextBoxValue(string controlID, string value)
        {
            TextBox oText = (TextBox)this.FindControl(controlID);
            if (oText != null)
                oText.Text = value;
            else
                oText.Text = "";
        }

        #endregion

        #region Ensynch Event Log

        private void SimpleLogFunction(string functionName, string Message, EventLogEntryType type, int eventID, short category)
        {
            using (StreamWriter mylog = new StreamWriter(@"C:\MyErrorLog.txt", true))
            {
                mylog.WriteLine(DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") + ", " + functionName + ", " + Message);
                mylog.Close();
            }
        }

        #endregion

    }
}
